<?php

namespace HPay;

use think\Log;


class HPayApiClient
{
    private $api;

    function __construct()
    {
        $this->api = new HPayApi();
    }

    /**
     * 支付接口
     * @param $amount
     * @param $userId
     * @param $orderSn
     * @param string $bankCode
     * @return mixed
     */
    public function payment($amount, $userId, $orderSn, $bankCode = HPayApiConstent::BANK_CODE_GCASH)
    {
        $apiPath = HPayApiConstent::API_PATH_TRANSFER;
        $data = [
            'payment_type' => HPayApiConstent::PAYMENT_TYPE_DIRECT,
            'amount' => $amount,
            'order_id' => $orderSn,
            'bank_code' => $bankCode,
            'callback_url' => $this->hostUrl() . HPayApiConstent::CALLBACK_URL,
            'return_url' => $this->hostUrl() . HPayApiConstent::RETURN_URL,
        ];
        Log::debug('hpay payment,params:' . json_encode($data));
        return $this->api->post($apiPath, $data);
    }

    /**
     * 验证回调签名
     * @param $params
     * @return false
     */
    public function checkCallbackSign($params)
    {
        if (empty($params) || empty($params['sign'])) {
            return false;
        }
        $sign = $this->api->callbackSign($params);
        Log::info('callback params:' . json_encode($params) . 'sign:' . $sign);
        return ($params['sign'] == $sign);
    }

    /**
     * 验证订单接口
     * @param $amount
     * @param $userId
     * @param $orderSn
     * @return mixed
     */
    public function check($amount, $orderSn)
    {
        $apiPath = HPayApiConstent::API_PATH_CHECK;
        $data = [
            'amount' => $amount,
            'out_trade_no' => $orderSn,
        ];
        Log::debug('paypy check,params:' . json_encode($data));
        return $this->api->post($apiPath, $data);
    }

    /**
     * 获取域名Url
     * @return string
     */
    private function hostUrl()
    {
        return url('/', '', '', true);
    }
}